<?php
namespace app\Controller;

use lib\View;
use app\Model\Album;

class AlbumController
{
	public function index()
	{
		$user = $_SESSION['user'];
		if (empty($user)) {
			header('Location:' . url('auth/register?op=2'));
			return;
		}
		// print_r($user);exit;
		$albumList = Album::get(['user.id' => $user->id]);
		return new View('album/index', ['user' => $user, 'albumList' => $albumList]);
	}

	public function logout()
	{
		unset($_SESSION['user']);
		header('Location:' . url('auth/register?op=2'));
	}

	public function create()
	{
		return new View('album/create');
	}

	public function cover()
	{
		$defaultCover = 'img' . DIRECTORY_SEPARATOR . 'timg.jpg';
			$artImg = isset($album->imageCollection[0]) ? $album->imageCollection[0] : null;
        	if (!empty($artImg)) {
            	$album->art = $artImg->path;
			}else $album->art = $defaultCover;
	}

	public function delete()
	{
		$id = $this->input('id');
		$album = Album::find(['id' => $id]);

		$filePath = STORAGE_DIR . DIRECTORY_SEPARATOR . 'album' . DIRECTORY_SEPARATOR . $id;
		foreach ($album->imageCollection as $image) {
			unlink(PUBLIC_DIR . DIRECTORY_SEPARATOR . $image->path);
		}
		unlink($filePath);
		header('Location:' . url('index'));
	}

	public function store()
	{
		//创建新相册
		$album = new Album();
		$album->id = $this->input('id');
		$album->title = $this->input('title');
		$album->description = $this->input('description');
		$album->create_at = time();
		$album->update_at = $album->create_at;

		$user = $_SESSION['user'];
		$album->user = $user;

		//上传图片
		$album->upload();
		//保存
		$album->save();
		header('Location:' . url('index'));
	}

	public function detail()
	{
		$id = $this->input('id');
		$album = Album::find(['id' => $id]);
		// return (new View('album.detail'))->with('album', $album);
		$user = $_SESSION['user'];
		return new View('album/detail', ['user' => $user , 'album' => $album]);
	}

	private function input($name)
    {
       	return htmlspecialchars(stripslashes($_REQUEST[$name]));
    }
}